package com.sanpu.kxe.business.main.presenter;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;

import com.orhanobut.dialogplus.DialogPlus;
import com.orhanobut.dialogplus.OnItemClickListener;
import com.sanpu.library.imagechoose.utils.PermissionsUtils;
import com.sanpu.kxe.R;
import com.sanpu.kxe.business.main.adapter.ShareAdapter;
import com.sanpu.kxe.business.main.bean.BrowserInput;
import com.sanpu.kxe.business.main.contract.BrowserX5Contract;
import com.sanpu.kxe.business.main.contract.MainConfig;
import com.sanpu.kxe.common.interfaces.UrlConstants;
import com.sanpu.kxe.jump.shareutil.ShareUtil;
import com.sanpu.kxe.jump.shareutil.share.ShareListener;
import com.sanpu.kxe.jump.shareutil.share.SharePlatform;
import com.sanpu.kxe.module.dialog.MaterialDialog;
import com.sanpu.kxe.module.dialog.interfaces.OnBtnClickL;
import com.sanpu.kxe.utils.FileUtil;
import com.sanpu.kxe.utils.ToastUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import rx.subscriptions.CompositeSubscription;

/**
 * Description：集成Tencent X5
 * Created by 薛勇军 on 2018/7/26.
 */

public class BrowserX5Presenter implements BrowserX5Contract.Presenter {

    private BrowserX5Contract.View mView;

    private MaterialDialog mDialog = null;

    private CompositeSubscription mSubscription;

    public BrowserX5Presenter(BrowserX5Contract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void initViewData(BrowserInput mInput) {
        if (mInput != null) {
            mView.showTitleLayout(mInput.getTitle(), mInput.isShowTitle());
            if (mInput.isShowPreLoad()) {
                mView.showPreLoading();
            }
            if (!TextUtils.isEmpty(mInput.getReferrer())) {
                Map<String, String> extraHeaders = new HashMap<>();
                extraHeaders.put(MainConfig.INTENT_REFERER, mInput.getReferrer());
                mView.loadUrl(mInput.getUrl(), extraHeaders);
            } else {
                if (!TextUtils.isEmpty(mInput.getUrl())) {
                    mView.loadUrl(mInput.getUrl());
                } else {
                    mView.loadDataWithBaseURL(mInput.getContent());
                }
            }
            if (mInput.isShowTitle() && !TextUtils.isEmpty(mInput.getUrl())
                    && mInput.getUrl().contains(UrlConstants.SHAREAPP)) {
                mView.showShareBtn();
            }
        }
    }

    @Override
    public void saveImageFile(final Bitmap bitmap) {
        if (mDialog == null) {
            mDialog = new MaterialDialog(mView.getContext());
            mDialog.title("提示").content("保存这个分享图片吗？").btnText("确定", "取消").show();
            mDialog.setOnBtnClickL(new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    if (!PermissionsUtils.checkWriteStoragePermission(mView.getContext()))
                        return;
                    File result = FileUtil.saveShareImageToGallery(mView.getContext(), bitmap);
                    ToastUtil.showTextViewPrompt(result != null ? "图片保存成功!请在相册查看" : "图片保存失败");
                    mDialog.dismiss();
                }
            }, new OnBtnClickL() {
                @Override
                public void onBtnClick() {
                    mDialog.dismiss();
                }
            });
        } else {
            if (mDialog.isShowing()) {
                mDialog.dismiss();
            }
        }
        mDialog.show();
    }

    @Override
    public void shareImageBitmap(final Bitmap bitmap) {
        final ShareAdapter mShareAdapter = new ShareAdapter(mView.getContext());
        DialogPlus dialog = DialogPlus.newDialog(mView.getContext())
                .setAdapter(mShareAdapter)
                .setHeader(R.layout.view_dialogplus_header)
                .setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(DialogPlus dialog, Object item, View view, int position) {
                        if (position < 0) return;
                        prepareImage(mShareAdapter.getItem(position).getPlatform(), bitmap);
                    }
                })
                .setExpanded(false)  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        dialog.show();
    }

    /**
     * 分享图片bitmap
     */
    private void prepareImage(final @SharePlatform.Platform int module, Bitmap mClipScreen) {
        ShareListener shareListener = new ShareListener() {
            @Override
            public void shareSuccess() {
                ToastUtil.showTextViewPrompt("分享成功！");
            }

            @Override
            public void shareFailure(Exception e) {
                ToastUtil.showTextViewPrompt(e.getMessage());
            }

            @Override
            public void shareCancel() {
            }
        };
        ShareUtil.shareImage(mView.getContext(), module, mClipScreen, shareListener);
    }

    @Override
    public void onDestroyPresenter() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
            mDialog = null;
        }
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
